﻿using System;
using System.Linq;
using System.Web.UI.WebControls;

namespace N2.Details
{
	using N2;
	using Engine;

	/// <summary>
	/// Dynamicaly typed version of the <c cref="EditableTypeListAttribute"/>
	/// </summary>
	[AttributeUsage(AttributeTargets.Class)]
	public class WithEditableTypeListAttribute: EditableDropDownAttribute
	{
		public Type BaseListItemType { get; set; }

		public WithEditableTypeListAttribute(string title, int sortOrder, Type baseListItemType)
			: base(title, sortOrder)
		{
			this.BaseListItemType = baseListItemType;
		}

		ITypeFinder m_typeFinder;

		ITypeFinder TypeFinder {
			get {
				return this.m_typeFinder
					?? (this.m_typeFinder = this.Engine.Resolve<ITypeFinder>());
			}
		}

		protected override ListItem[] GetListItems()
		{
			return (
				from _type in this.TypeFinder.Find(this.BaseListItemType)
				where !_type.IsAbstract && !_type.ContainsGenericParameters
				select new ListItem(
					_type.FullName,
					_type.AssemblyQualifiedName)
			).ToArray();
		}

		//DropDownList can only hold strings, so we need to convert System.Type back and forth
		protected override object GetValue(ListControl ddl)
		{
			return base.GetValue(ddl) as string;
		}

		protected override string GetValue(ContentItem item)
		{
			return item[Name] as string;
		}
	}
}
